package cn.bonoon.kernel.expression.results;

import org.batatasframework.web.RequestParameterReader;

import cn.bonoon.kernel.expression.ExpressionParseContext;
import cn.bonoon.kernel.expression.ExpressionValue;
import cn.bonoon.kernel.support.IOperator;

public class RequestExpressionValue implements ExpressionValue{
	
	private final String name;
	private final String type;
	
	public RequestExpressionValue(ExpressionParseContext context, String name, String type){
		this.name = name;
		this.type = type;
	}

	public RequestExpressionValue(ExpressionParseContext context, String name){
		this(context, name, null);
	}

	@Override
	public Object value(IOperator operator, RequestParameterReader parameterReader, Object defaultValue) {
		Object val = internalValue(parameterReader);
		return val == null ? defaultValue : val;
	}

	private Object internalValue(RequestParameterReader parameterReader) {
		if(null != type){
			switch (type) {
			case "I":
			case "B":
			case "C":
			case "S":
				return parameterReader.getInteger(name);
			case "J":
				return parameterReader.getLong(name);
			case "F":
			case "D":
				return parameterReader.getDouble(name);
			case "Z":
				return parameterReader.getBoolean(name);
			case "DT":
				return parameterReader.getDate(name, null);
			}
		}
		return null;
	}
}
